﻿using System;

class Program
{
    //使用2-2的整数生成器
    static void Main(string[] args)
    {
        Generate();
        var numbers = ReadNumbersFromFile();
        // LINQ
        var sortedNumbers = numbers.OrderByDescending(n => n).ToList();
        int sum = sortedNumbers.Sum();
        double average = sortedNumbers.Average();
        
        Console.WriteLine($"和为:{sum}");
        Console.WriteLine($"平均数为:{average}");
        WriteResultToFile(sortedNumbers);
        Console.WriteLine("排序后的数组已写入到result.txt 文件中");

    }
    private static void Generate()
    {
        //生成随机数的方法
        using (StreamWriter writer = new StreamWriter("Generator.txt"))
        {
            Random random = new Random();
            for (int i = 0; i < 100; i++)
            {
                int number = random.Next(1000);
                writer.WriteLine(number);
            }
        }
    }
    static List<int> ReadNumbersFromFile()
    {
        List<int> numbers = new List<int>();
        string filePath = "Generator.txt";

        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (int.TryParse(line, out int number))
                {
                    numbers.Add(number);
                }
            }
        }
        return numbers;
    }
    static void WriteResultToFile(List<int> sortedNumbers)
    {
        using (StreamWriter writer = new StreamWriter("result.txt"))
        {
            foreach (var number in sortedNumbers)
            {
                writer.WriteLine(number);
            }
        }
    }
}